<template>
  <div class="edit-page-wrap">
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="edit-form-wrap"
        >
          <el-form-item label="归属企业" prop="orgCom">
            <!-- <qc-select
              v-if="!id"
              :value="ruleForm.orgId"
              :remote="true"
              :filterable="true"
              :options="optionsS.org"
              placeholder="请选择归属企业"
              @change="handleChangeOrg"
            >
            </qc-select> -->
            <el-cascader
              v-if="!id"
              ref="orgRef"
              class="heard-org"
              v-model="ruleForm.orgCom"
              :show-all-levels="false"
              :options="optionsS.org"
              @change="handleChangeOrg"
              placeholder="请选择归属企业"
              :props="{ value: 'id', checkStrictly: true }"
            />
            <div v-else>
              {{ ruleForm.orgId ? ruleForm.orgName : ruleForm.channelName }}
            </div>
          </el-form-item>
          <el-form-item label="管理员姓名" prop="accountName">
            <el-input
              v-model.trim="ruleForm.accountName"
              placeholder="请输入管理员姓名"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="管理员账号" prop="accountCode">
            <el-input
              v-if="!id"
              v-model.trim="ruleForm.accountCode"
              placeholder="请输入管理员账号"
              maxlength="30"
              clearable
            />
            <div v-else>{{ ruleForm.accountCode }}</div>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model.trim="ruleForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
              clearable
            />
          </el-form-item>
          <el-form-item v-if="!id" label="密码" prop="password">
            <el-input
              v-model.trim="ruleForm.password"
              placeholder="请输入密码"
              maxlength="30"
              show-password
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="edit-form-wrap"
        >
          <el-form-item label="选择角色" prop="roleId">
            <!-- <QcTree
              :setCheckedKeys="ruleForm.roleIds"
              :data="optionsS.roleTree"
              :showCheckbox="true"
              @handleCheck="handleCheckRole"
            ></QcTree> -->
            <qc-select
              :value="ruleForm.roleId"
              :remote="true"
              :filterable="true"
              :options="optionsS.roleTree"
              placeholder="请选择角色"
              @change="handleCheckRole"
            >
            </qc-select>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
// import QcTree from '@/components/qcTree/index.vue';
import { FormRules, FormInstance } from 'element-plus';
import { IS_PHONE_NUM } from '@/utils/verify';
import {
  queryRoleTree,
  saveAccount,
  updateAccount,
  queryByAccountId,
} from '@/service/apis/auth';
import { selectOrgTreeData } from '@/service/apis/api';
import { getMd5 } from '@/utils/utils';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();

const optionsS = reactive({
  org: [] as any,
  roleTree: [] as any,
});

// 获取归属运营商数据
const getOrg = () => {
  const obj: any = {};
  const cid = window.localStorage.getItem('channelId');
  const oid = window.localStorage.getItem('orgId');
  if (cid) {
    obj.channelId = cid;
  }
  if (oid) {
    obj.orgId = oid;
  }
  selectOrgTreeData(obj).then((res: any) => {
    // if (oid) {
    //   optionsS.org = res[0].children[0].children;
    // } else if (cid) {
    //   optionsS.org = res[0].children;
    // } else {
    //   optionsS.org = res;
    // }
    optionsS.org = res;
  });
};

// 获角色树数据
const getRoleTree = () => {
  queryRoleTree({}).then((res: any) => {
    optionsS.roleTree = res.map((item: any) => ({
      label: item.label,
      value: item.id,
    }));
  });
};

getOrg();

const ruleForm: any = reactive({
  id: '',
  orgCom: '', // 归属企业
  channelId: '', // 平台传值-100
  orgId: '',
  orgName: '',
  channelName: '',
  accountName: '', //管理员姓名
  accountCode: '', //管理员账号
  phone: '', // 手机号
  password: '', //密码
  roleIds: [] as any, //选择角色
  roleId: undefined as any,
});

const rules = reactive<FormRules>({
  orgCom: [
    { required: true, message: '请选择归属企业', trigger: ['blur', 'change'] },
  ],
  accountName: [
    { required: true, message: '请输入管理员姓名', trigger: 'blur' },
  ],
  accountCode: [
    { required: true, message: '请输入管理员账号', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: IS_PHONE_NUM,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  // roleIds: [
  //   { required: true, message: '请选择选择角色', trigger: ['blur', 'change'] },
  // ],
  roleId: [
    { required: true, message: '请选择选择角色', trigger: ['blur', 'change'] },
  ],
});

const orgRef = ref();
const handleChangeOrg = (e: any) => {
  const data = orgRef.value.getCheckedNodes()[0].data;
  if (data.parentId === '-100') {
    // 平台
    ruleForm.channelId = '-100';
    ruleForm.orgId = '';
  } else if (data.type === 'CHANNEL') {
    // 渠道
    ruleForm.channelId = data.id;
    ruleForm.orgId = '';
  } else {
    // 企业
    ruleForm.channelId = data.referenceId;
    ruleForm.orgId = data.id;
  }
};

// const handleCheckRole = (
//   data: any,
//   checkedData: any,
//   checkedChildData: any
// ) => {
//   ruleForm.roleIds = checkedChildData;
// };
const handleCheckRole = (e: any) => {
  ruleForm.roleId = e;
};

if (id) {
  queryByAccountId({ id: id }).then((res: any) => {
    for (const key in ruleForm) {
      if (res[key]) {
        ruleForm[key] = res[key];
      }
    }
    ruleForm.roleId = ruleForm.roleIds[0];
    ruleForm.orgCom = ruleForm.orgId || ruleForm.channelId;

    optionsS.roleTree = res.roleList.map((item: any) => ({
      label: item.label,
      value: item.id,
    }));
  });
} else {
  getRoleTree();
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormRef1.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  const form = { ...ruleForm };
  form.password = getMd5(ruleForm.password);
  form.roleIds = [form.roleId];
  console.log('ru---', form);
  if (id) {
    delete form.password;
    updateAccount(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveAccount(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>